package com.yangff.filter;

import com.yangff.entity.dto.AuthDTO;
import com.yangff.entity.vo.JwtVo;
import com.yangff.utils.JwtUtil;
import com.yangff.utils.RedisUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;


@Component
@Slf4j
@RequiredArgsConstructor
public class GlobalLoginFilter implements GlobalFilter, Ordered {

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    private final RabbitTemplate rabbitTemplate;






    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path =  request.getPath().toString();
        if (checkPathIsLogin(path)) {
            //登录页面不需要校验，放行
            return chain.filter(exchange);
        }



        //String account = request.getQueryParams().getFirst("account");

        HttpHeaders headers = request.getHeaders();
        String token = null;
        List<String> authorization = headers.get("authorization");
        List<String> infoType = headers.get("info-type");
        List<String> infoAccount = headers.get("info-account");

        //不要前面的bearer
        if (authorization != null && authorization.isEmpty() == false) {
            token = authorization.get(0).split(" ")[1];
        }


        //检测判断
        JwtVo jwtVo = new JwtVo();
        try {
            jwtVo = JwtUtil.checkJwtToken(token);

            if(infoAccount.get(0).equals(jwtVo.getAccount()) == false) throw new Exception("账号信息不匹配");
            if((infoType.get(0).equals("admin") && jwtVo.getType().equals("user"))
            || (infoType.get(0).equals("user") && jwtVo.getType().equals("admin")))
            throw new Exception("账号信息不匹配");

            //if(jwtVo.getAccount() != account) throw new Exception("账号信息不匹配");
        } catch (Exception e) {
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);

            //检查该清除哪一类账号缓存
            if(path.contains("admin")) rabbitTemplate.convertAndSend("fts.direct","delete_admintoken",jwtVo);
            else rabbitTemplate.convertAndSend("fts.direct","delete_usertoken",jwtVo);


            return response.setComplete();
        }


        String account = jwtVo.getAccount();
        //赋值给threadlocal
        AuthDTO.set(account);

        //向下传递账号信息
        ServerWebExchange webExchange = exchange.mutate()
                .request(builder -> builder.header("account", account))
                .build();


        return chain.filter(webExchange);
    }

    private boolean checkPathIsLogin(String toString) {
        List<String> list = List.of("/**/login", "/**/register");
        for (String s : list) {
            if (antPathMatcher.match(s, toString)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
